package login

import (
	"fmt"
	clin "github.com/AnonymousMister/go-gitlab-client/v2/gitlab"
	"github.com/urfave/cli/v2"
	"gitlab-cli/gitlab"
)

var Login = &cli.Command{
	Name:   "login",
	Usage:  "登录gitlab",
	Action: action,
	Flags:  flag(),
}

func action(c *cli.Context) error {
	token := c.String("token")
	url := c.String("url")
	newGitlab := clin.NewGitlab(url, "", token)
	u, _, e := newGitlab.CurrentUser()
	if e != nil {
		return e
	}
	if e := gitlab.SaveClient(u, token, url); e != nil {
		return e
	}
	fmt.Print("成功登录!")
	return nil
}

func flag() []cli.Flag {
	flag := []cli.Flag{
		&cli.StringFlag{
			Name:    "token",
			Aliases: []string{"t"},
			Usage:   "访问token设置",
		},
		&cli.StringFlag{
			Name:    "url",
			Aliases: []string{"u"},
			Usage:   "设置gitlab的访问域名",
		},
	}
	return flag
}
